import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import store from '@/store'


function hasUrl(url: any, next: any) {
  let result = store.getters.getUser.menus_url.some((item: any) => item == url)
  if (result) {
    next()
  } else {
    next('/home')
  }
}

export const indexRoutes = [
  {
    path: '/menu',
    component: () => import('../views/menu/menu.vue'),
    meta: {
      title: '菜单管理'
    },
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl('/menu', next)
    }
  },
  {
    path: '/role',
    component: () => import('../views/role/role.vue'),
    meta: {
      title: '角色管理'
    },
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl('/role', next)
    }
  },
  {
    path: '/user',
    component: () => import('../views/user/user.vue'),
    meta: {
      title: '管理员管理'
    },
    beforeEnter: (to: any, from: any, next: any) => {
      hasUrl('/user', next)
    }
  },
  {
    path: '/cate',
    component: () => import('../views/cate.vue'),
    meta: {
      title: '菜单分类'
    },
  },
  {
    path: '/specs',
    component: () => import('../views/specs.vue'),
    meta: {
      title: '商品规格'
    },
  },
  {
    path: '/goods',
    component: () => import('../views/goods.vue'),
    meta: {
      title: '商品管理'
    },
  },
  {
    path: '/member',
    component: () => import('../views/member.vue'),
    meta: {
      title: '会员管理'
    },
  },
  {
    path: '/banner',
    component: () => import('../views/banner.vue'),
    meta: {
      title: '轮播图管理'
    },
  },
  {
    path: '/seckill',
    component: () => import('../views/seckill.vue'),
    meta: {
      title: '秒杀活动'
    },
  },
  {
    path: '/map',
    component: () => import('../views/map.vue'),
    meta: {
      title: '高德地图'
    },
  },
  {
    path: '/test1',
    component: () => import('../views/test1.vue'),
    meta: {
      title: '测试1'
    },
  },
  {
    path: '/test2',
    component: () => import('../views/test2.vue'),
    meta: {
      title: '测试2'
    },
  }
]

const routes: Array<RouteRecordRaw> = [
  {
    path: '/index',
    component: () => import('../pages/index.vue'),
    children: [
      {
        path: '/home',
        component: () => import('../views/home.vue')
      },
      ...indexRoutes,
      {
        path: '',
        redirect: '/home'
      }
    ]
  },
  {
    path: '/login',
    component: () => import('../pages/login.vue')
  },
  {
    path: '',
    redirect: '/index'
  }
]


const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 全局登录拦截
router.beforeEach((to, from, next) => {
  if (to.path == '/login') {
    next()
    return
  }
  if (store.getters.getUser) {
    next()
    return
  }
  next('/login')
})


export default router
